package server.netty.websocket;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.apache.http.util.ByteArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.business.commend.ScmdWebsocketHandler;
import server.netty.websocket.attr.WsChannelAttrKey;
import server.netty.websocket.attr.WsRequestInfo;
import server.protobuf.CSLogin;
import server.protobuf.UserInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Websocket Handler 处理请求
 */
public class TextWebSocketFrameHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(TextWebSocketFrameHandler.class);
    private final ChannelGroup group;

    public TextWebSocketFrameHandler(){
        group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);//通道组
        ScmdWebsocketHandler.getInstance().setChannelGroup(group);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ScmdWebsocketHandler.getInstance().dispatchWebsocketMessage(msg.toString());
        LOGGER.info("数据内容"+msg);

        if (msg instanceof CSLogin.CSLoginInfo ){
            CSLogin.CSLoginInfo clientReq = (CSLogin.CSLoginInfo)msg;
            String user_name = clientReq.getUserName();
            String pass_word = clientReq.getPassword();
            System.out.println("数据内容：UserName="+user_name+",Password="+pass_word);

             CSLogin.CSLoginRes.Builder info_res = CSLogin.CSLoginRes.newBuilder();
             info_res.setResultCode(200);
            byte[] bytes = info_res.build().toByteArray();
            byte[] int1 = intToByte(8);
            byte[] int2 = intToByte(1000102);


            byte[] bytes1 = byteMergerAll(int1, int2, bytes);
            ByteBuf bytebuf = Unpooled.buffer();
            bytebuf.writeBytes(bytes1);
            BinaryWebSocketFrame binaryWebSocketFrame=new BinaryWebSocketFrame(bytebuf);
            ctx.channel().writeAndFlush(binaryWebSocketFrame);



        }




    }


    public byte[] intToByte( int val){
        byte[] b = new byte[4];
        b[0] = (byte)(val & 0xff);
        b[1] = (byte)((val >> 8) & 0xff);
        b[2] = (byte)((val >> 16) & 0xff);
        b[3] = (byte)((val >> 24) & 0xff);
        return b;
    }


    //整合数组
    private static byte[] byteMergerAll(byte[]... values) {
        int length_byte = 0;
        for (int i = 0; i < values.length; i++) {
            length_byte += values[i].length;
        }
        byte[] all_byte = new byte[length_byte];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] b = values[i];
            System.arraycopy(b, 0, all_byte, countLength, b.length);
            countLength += b.length;
        }
        return all_byte;
    }



    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //握手成功，连接建立，否则交由父类默认处理不符合协议的通讯
        if(evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE){
            //连接验证
            group.add(ctx.channel());
            ctx.pipeline().remove(HttpRequestHandler.class);
            //分发ws连接初始化事件
            WsRequestInfo ws = ctx.channel().attr(WsChannelAttrKey.WS_REQUEST_ATTR_KEY).get();
            if(ws != null){
                ScmdWebsocketHandler.getInstance().dispatchWebsocketOpen(ctx.channel());
            }
        } else{
            super.userEventTriggered(ctx, evt);
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

/*        new Thread(new Runnable() {
            @Override
            public void run() {
                CSLogin.CSLoginInfo.Builder info_builder = CSLogin.CSLoginInfo.newBuilder();
                info_builder.setUserName("linshuhe");
                info_builder.setPassword("123456");
                CSLogin.CSLoginInfo info = info_builder.build();
                ctx.writeAndFlush(info);
                LOGGER.info("发送数据成功");


            }
        }).start();  // why 要异步？ 握手时间太长了？*/




    }




    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        group.remove(ctx.channel());
        ScmdWebsocketHandler.getInstance().dispatchWebsocketClose(ctx.channel());
        super.handlerRemoved(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        group.remove(ctx.channel());
        ScmdWebsocketHandler.getInstance().dispatchWebsocketClose(ctx.channel());
        super.exceptionCaught(ctx, cause);
    }




}
